<template>
  <view class="container">
   

    <!-- 筛选栏 -->
    <view class="filter-container">
      <view class="filter-bar">
        <view class="filter-item">
          <picker mode="date" fields="month" :value="selectedMonth" @change="onMonthChange">
            <view class="picker-wrapper">
              <uni-icons type="calendar" size="18" color="#999"></uni-icons>
              <text class="picker-text">{{ selectedMonth ? selectedMonth : '选择年月' }}</text>
              <uni-icons type="down" size="14" color="#999"></uni-icons>
            </view>
          </picker>
        </view>
        <view class="filter-item">
          <picker :range="typeOptions" :value="selectedTypeIndex" @change="onTypeChange">
            <view class="picker-wrapper">
              <uni-icons type="list" size="18" color="#999"></uni-icons>
              <text class="picker-text">{{ typeOptions[selectedTypeIndex] }}</text>
              <uni-icons type="down" size="14" color="#999"></uni-icons>
            </view>
          </picker>
        </view>
      </view>
    </view>

    <!-- 明细列表 -->
    <view class="history-container">
      <view class="history-list" :class="{ 'empty-list': records.length === 0 }">
        <view 
          v-for="item in records" 
          :key="item._id" 
          class="history-item"
          :class="item.type"
          @click="showDetail(item)"
        >
          <view class="item-content">
            <view class="item-header">
              <text class="type-text" :class="item.type">{{ getTypeText(item) }}</text>
              <text class="amount" :class="item.type">
                {{ (item.type === 'recharge' || item.type === 'task_income') ? '+' : '-' }}¥{{ item.amount }}
              </text>
            </view>
            <view class="item-footer">
              <text class="desc">{{ getDesc(item) }}</text>
              <text class="date">{{ formatDate(item.create_time) }}</text>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="records.length === 0" class="empty-state">
          <view class="empty-icon">
            <uni-icons type="empty" size="80" color="#E5E5E5"></uni-icons>
          </view>
          <text class="empty-text">暂无交易记录</text>
          <text class="empty-desc">完成交易后将在此显示记录</text>
          <button class="recharge-btn" @click="navigateToRecharge">立即充值</button>
        </view>
      </view>
    </view>

    <!-- 下拉刷新提示 -->
    <view class="refresh-tip" v-if="refreshing">
      <uni-icons type="refresh" size="16" color="#fff"></uni-icons>
      <text>刷新中...</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      records: [],
      selectedMonth: '',
      typeOptions: ['全部', '充值', '支出', '收入'],
      selectedTypeIndex: 0,
      refreshing: false
    }
  },
  async onShow() {
    await this.fetchRecords()
  },
  methods: {
    async fetchRecords() {
      try {
        this.refreshing = true

        // 构建筛选参数
        const params = {}

        // 处理月份筛选（确保格式正确）
        if (this.selectedMonth) {
          // 提取年月部分（YYYY-MM）
          const [year, month] = this.selectedMonth.split('-')
          params.month = `${year}-${month}`
        }

        // 处理类型筛选
        if (this.selectedTypeIndex === 1) {
          params.type = 'recharge' // 充值
        } else if (this.selectedTypeIndex === 2) {
          params.type = 'task_publish' // 支出
        } else if (this.selectedTypeIndex === 3) {
          params.type = 'task_income' // 收入
        }
        // selectedTypeIndex === 0 时，不设置 type 参数，查询所有类型

        const res = await uniCloud.callFunction({
          name: 'getPaymentRecords',
          data: params
        })

        if (res.result.code === 200) {
          this.records = res.result.data || []
        } else {
          uni.showToast({ title: res.result.msg || '获取明细失败', icon: 'none' })
        }
      } catch (error) {
        uni.showToast({ title: '获取明细失败', icon: 'none' })
        console.error('获取明细失败：', error)
      } finally {
        this.refreshing = false
      }
    },

    // 月份筛选变更
    onMonthChange(e) {
      this.selectedMonth = e.detail.value
      this.fetchRecords()
    },

    // 类型筛选变更
    onTypeChange(e) {
      this.selectedTypeIndex = Number(e.detail.value)
      this.fetchRecords()
    },

    // 返回上一页
    navigateBack() {
      uni.navigateBack()
    },

    // 跳转到充值页面
    navigateToRecharge() {
      uni.navigateTo({
        url: '/pages/user/wallet/wallet'
      })
    },

    // 显示交易详情
    showDetail(item) {
      // 这里可以添加交易详情弹窗或跳转详情页
      console.log('交易详情:', item)
    },

    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      // 补足两位数
      const pad = n => n < 10 ? '0' + n : n
      return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
    },
    getTypeText(item) {
      switch (item.type) {
        case 'recharge': return '充值'
        case 'task_publish': return '任务发布'
        case 'task_income': return '任务收入'
        default: return '其他'
      }
    },
    getDesc(item) {
      if (item.type === 'recharge') return '钱包充值'
      if (item.type === 'task_publish') return '发布任务'
      if (item.type === 'task_income') return '完成任务收入'
      return ''
    },
    getIconColor(type) {
      if (type === 'recharge') return '#52C41A' // 绿色 - 充值
      if (type === 'task_income') return '#1890FF' // 蓝色 - 任务收入
      return '#FA8C16' // 橙色 - 支出
    }
  }
}
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #F9F9F9;
  padding: 0;
}



.back-btn {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

/* 筛选栏样式 */
.filter-container {
  padding: 20rpx 30rpx;
  background: #FFFFFF;
}

.filter-bar {
  display: flex;
  gap: 20rpx;
}

.filter-item {
  flex: 1;
  background: #F5F5F5;
  border-radius: 12rpx;
  padding: 15rpx 20rpx;
  position: relative;
}

.picker-wrapper {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.picker-text {
  font-size: 28rpx;
  color: #666;
  flex: 1;
}

/* 列表容器样式 */
.history-container {
  padding: 20rpx 30rpx;
}

.history-list {
  background: #FFFFFF;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.history-item {
  padding: 30rpx;
  border-bottom: 1rpx solid #F5F5F5;
  transition: all 0.2s ease;
}

.history-item:last-child {
  border-bottom: none;
}

.history-item:active {
  background: #F8F8F8;
}

/* 充值样式 - 绿色 */
.recharge .type-text, .recharge .amount {
  color: #52C41A;
}

/* 任务收入样式 - 蓝色 */
.task_income .type-text, .task_income .amount {
  color: #1890FF;
}

/* 任务发布样式 - 橙色 */
.task_publish .type-text, .task_publish .amount {
  color: #FA8C16;
}

/* 列表项内容样式 */
.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.type-text {
  font-size: 30rpx;
  font-weight: 500;
}

.amount {
  font-size: 32rpx;
  font-weight: 600;
}

.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.desc {
  font-size: 26rpx;
  color: #999;
}

.date {
  font-size: 24rpx;
  color: #C0C4CC;
}

/* 空状态样式 */
.empty-state {
  padding: 80rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.empty-icon {
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.recharge-btn {
  background: linear-gradient(135deg, #00BFFF, #0099FF);
  color: #FFFFFF;
  font-size: 28rpx;
  font-weight: 500;
  padding: 20rpx 80rpx;
  border-radius: 40rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 153, 255, 0.2);
}

/* 刷新提示样式 */
.refresh-tip {
  position: fixed;
  top: 20rpx;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.7);
  color: #FFFFFF;
  padding: 15rpx 30rpx;
  border-radius: 100rpx;
  display: flex;
  align-items: center;
  gap: 10rpx;
  z-index: 100;
  opacity: 0;
  animation: fadeIn 0.3s forwards;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translate(-50%, -20rpx); }
  to { opacity: 1; transform: translate(-50%, 0); }
}

/* 动画效果 */
.history-item {
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from { opacity: 0; transform: translateY(20rpx); }
  to { opacity: 1; transform: translateY(0); }
}
</style>